import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Modal,
  Form,
  Input,
  message,
  Badge,
  Avatar,
  Tooltip,
} from "antd"
import { useState, useEffect } from "react"
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  CommentOutlined,
  UserOutlined,
  CalendarOutlined,
} from "@ant-design/icons"
import PageHeaderWrapper from "@/components/pageHeaderWrapper"
import "./index.less"

const { TextArea } = Input

function SubordinateDailyReport() {
  const [form] = Form.useForm()
  const [reports, setReports] = useState([])
  const [loading, setLoading] = useState(false)
  const [commentModalVisible, setCommentModalVisible] = useState(false)
  const [selectedReport, setSelectedReport] = useState(null)

  // 获取下属日报列表
  const fetchReports = async () => {
    setLoading(true)
    try {
      // 替换为实际API调用
      const response = await fetch("/api/subordinate-reports")
      const data = await response.json()
      setReports(data)
    } catch (error) {
      message.error("获取日报列表失败")
    } finally {
      setLoading(false)
    }
  }

  // 处理日报审批
  const handleApprove = async (reportId, approved) => {
    try {
      await fetch(`/api/reports/${reportId}/approve`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ approved }),
      })
      message.success(approved ? "审批通过" : "审批拒绝")
      fetchReports()
    } catch (error) {
      message.error("审批操作失败")
    }
  }

  // 处理评论提交
  const handleComment = async (values) => {
    try {
      await fetch(`/api/reports/${selectedReport.id}/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      })
      message.success("评论提交成功")
      setCommentModalVisible(false)
      form.resetFields()
      fetchReports()
    } catch (error) {
      message.error("评论提交失败")
    }
  }

  // 表格列定义
  const columns = [
    {
      title: "员工",
      dataIndex: "employee",
      key: "employee",
      render: (employee) => (
        <Space>
          <Avatar src={employee.avatar} icon={<UserOutlined />} />
          <span>{employee.name}</span>
        </Space>
      ),
    },
    {
      title: "日期",
      dataIndex: "date",
      key: "date",
      render: (date) => new Date(date).toLocaleDateString(),
    },
    {
      title: "工作内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        const statusMap = {
          pending: { color: "orange", text: "待审批" },
          approved: { color: "green", text: "已通过" },
          rejected: { color: "red", text: "已拒绝" },
        }
        const { color, text } = statusMap[status]
        return <Tag color={color}>{text}</Tag>
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          {record.status === "pending" && (
            <>
              <Button
                type="link"
                icon={<CheckCircleOutlined />}
                onClick={() => handleApprove(record.id, true)}
              >
                通过
              </Button>
              <Button
                type="link"
                danger
                icon={<CloseCircleOutlined />}
                onClick={() => handleApprove(record.id, false)}
              >
                拒绝
              </Button>
            </>
          )}
          <Button
            type="link"
            icon={<CommentOutlined />}
            onClick={() => {
              setSelectedReport(record)
              setCommentModalVisible(true)
            }}
          >
            评论
          </Button>
        </Space>
      ),
    },
  ]

  useEffect(() => {
    fetchReports()
  }, [])

  return (
    <>
      <PageHeaderWrapper title="下属日报" subtitle="查看和审批下属的日报" />
      <section className="G-main">
        <Card>
          <Table
            columns={columns}
            dataSource={reports}
            loading={loading}
            rowKey="id"
            pagination={{
              defaultPageSize: 10,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
          />
        </Card>

        <Modal
          title="日报评论"
          open={commentModalVisible}
          onOk={() => form.submit()}
          onCancel={() => {
            setCommentModalVisible(false)
            form.resetFields()
          }}
        >
          <Form form={form} layout="vertical" onFinish={handleComment}>
            <Form.Item
              name="comment"
              label="评论内容"
              rules={[{ required: true, message: "请输入评论内容" }]}
            >
              <TextArea rows={4} />
            </Form.Item>
          </Form>
        </Modal>
      </section>
    </>
  )
}

export default SubordinateDailyReport
